package com.xsq.newmall01.ServiceImpl.UserServiceImpl;

import com.xsq.newmall01.Dao.User;
import com.xsq.newmall01.Exception.ServiceException;
import com.xsq.newmall01.Mapper.UserMapper;
import com.xsq.newmall01.Service.UserService.UUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("userservice")
public class UUserServiceImpl implements UUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(User user) {
        // 调用mapper验证用户是否存在（登录逻辑）
        return userMapper.isuserexist(user);
    }

    @Override
    public void updateUser(User user) {
        // 1. 校验昵称长度
        if (user.getNickname() != null && user.getNickname().length() > 7) {
            throw new ServiceException("昵称长度不能超过7个字符");
        }

        // 2. 校验手机号格式
        if (user.getPhone() != 0 && !isValidPhone(String.valueOf(user.getPhone()))) {
            throw new ServiceException("手机号格式错误（需11位数字）");
        }

        // 3. 校验邮箱格式
        if (user.getEmail() != null && !isValidEmail(user.getEmail())) {
            throw new ServiceException("邮箱格式错误（例如：xxx@xxx.com）");
        }
        // 调用mapper更新用户信息
        userMapper.updateuser(user);
    }
    // 复用手机号和邮箱校验方法
    private boolean isValidPhone(String phone) {
        return phone.matches("^1[3-9]\\d{9}$");
    }

    private boolean isValidEmail(String email) {
        return email.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$");
    }

}
